﻿using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;

//using NPOI.HSSF.UserModel;
//using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

namespace NB_Controller_Test
{
    class GlobalFun
    {
        #region CRC Fun
        private static UInt32[] crc32_Tab = null;//new UInt32[256];
        // Table of CRC constants - implements x^16+x^12+x^5+1
        private static readonly UInt16[] crc16_tab = new UInt16[]
        {
            #region CRC Table
            0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, 
            0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, 
            0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, 
            0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, 
            0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, 
            0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, 
            0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, 
            0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, 
            0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, 
            0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, 
            0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, 
            0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, 
            0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, 
            0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, 
            0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, 
            0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, 
            0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, 
            0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, 
            0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, 
            0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, 
            0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, 
            0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 
            0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, 
            0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, 
            0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, 
            0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, 
            0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, 
            0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, 
            0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, 
            0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, 
            0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, 
            0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0, 
            #endregion
        };

        private static byte Calcrc_1byte(byte abyte)
        {
            byte i, crc_1byte;
            crc_1byte = 0;
            for (i = 0; i < 8; i++)
            {
                if (((crc_1byte ^ abyte) & 0x01) != 0)
                {
                    crc_1byte ^= 0x18;
                    crc_1byte >>= 1;
                    crc_1byte |= 0x80;
                }
                else
                    crc_1byte >>= 1;

                abyte >>= 1;
            }

            return crc_1byte;
        }

        public static byte OppCalcCRC(byte[] p, UInt16 dataLen, UInt16 offset)
        {
            byte crc = 0;
            byte cur;
            UInt16 index = offset;

            while ((dataLen--) != 0)
            {
                cur = (byte)(p[index++]);
                crc = Calcrc_1byte((byte)(crc ^ cur));
            }
            return crc;
        }

        public static UInt16 OppCalcCRC16(byte[] buf, UInt16 len)
        {
            UInt16 crc = 0;
            UInt16 i;
            UInt16 tabval;
            int idx = 0;

            if (len > buf.Length)
                return crc;

            for (i = 0; i < len; i++)
            {
                tabval = buf[i];
                idx = ((crc >> 8) ^ tabval) & 0xFF;
                crc = (UInt16)(crc16_tab[idx] ^ (crc << 8));
            }
            return crc;
        }

        public static UInt16 OppCalcCRC(byte[] pui16_Data, int ui16_lenth)
        {
            byte i;
            UInt16 crc = 0;
            UInt16 lenth;

            lenth = (UInt16)ui16_lenth;

            int j = 0;
            UInt16 tmp;
            while (lenth > 0)
            {
                //crc = crc ^ ((UInt16)(*pui16_Data++) << 8);
                tmp = pui16_Data[j++];
                crc = (UInt16)(crc ^ (tmp << 8));

                i = 8;
                do
                {
                    if ((crc & 0x8000) > 0)
                    {
                        crc = (UInt16)((crc << 1) ^ 0x1021);
                    }
                    else
                    {
                        crc <<= 1;
                    }
                } while ((--i) > 0);
                lenth--;
            }
            return (crc);
        }

        public static UInt16 CalcCRC(byte[] pui16_Data, int startOffset, int ui16_lenth)
        {
            byte i;
            UInt16 crc = 0;
            UInt16 lenth;

            lenth = (UInt16)ui16_lenth;

            int j = startOffset;
            UInt16 tmp;
            while (lenth > 0)
            {

                //crc = crc ^ ((UInt16)(*pui16_Data++) << 8);
                tmp = pui16_Data[j++];
                crc = (UInt16)(crc ^ (tmp << 8));

                i = 8;
                do
                {
                    if ((crc & 0x8000) > 0)
                    {
                        crc = (UInt16)((crc << 1) ^ 0x1021);
                    }
                    else
                    {
                        crc <<= 1;
                    }
                } while ((--i) > 0);
                lenth--;
            }
            return (crc);
        }

        public static UInt32 OppCalcCRC32(byte[] pImage, UInt32 imageSize, UInt32 crc = 0xFFFFFFFF)
        {
            if (crc32_Tab == null)
            {
                crc32_Tab = new UInt32[256];
                InitCrc32Table(crc32_Tab);
            }

            if (imageSize > pImage.Length)
                return crc;

            for (int i = 0; i < imageSize; i++)
            {
                crc = crc32_Tab[(crc ^ pImage[i]) & 0xFF] ^ (crc >> 8);
            }
            return crc;
        }

        private static void InitCrc32Table(UInt32[] pCRCTable)
        {
            //256
            UInt32 c;
            UInt32 i, j;

            for (i = 0; i < 256; i++)
            {
                c = i;
                for (j = 0; j < 8; j++)
                {
                    if ((c & 1) > 0)
                    {
                        c = (UInt32)0xedb88320L ^ (c >> 1);
                    }
                    else
                    {
                        c = c >> 1;
                    }
                }
                pCRCTable[i] = c;
            }
        }
        #endregion

        #region BasicType<->ByteArray
        /*
         * 基本类型转换为字节数组，大端模式
         *  basicType  要转换的基本类型
          * bufOut     转换后存储的缓冲区
          * startOffset 起始偏移 量
          * endOffsetOut endOffsetOut[0] 转换到缓冲区后，缓冲区可用起始便宜
         * */
        public static Boolean BasicTypeToByteArrayEndian(object basicType, byte[] bufOut, int startOffset, out int endOffsetOut)
        {
            TypeCode typeCode;
            typeCode = Type.GetTypeCode(basicType.GetType());  // get type
            byte[] temp;
            int offset = startOffset;
            switch (typeCode)
            {
                case TypeCode.Single: // float
                    {
                        temp = BitConverter.GetBytes((Single)basicType);
                        Array.Reverse(temp);
                        Array.Copy(temp, 0, bufOut, offset, sizeof(Single));
                        endOffsetOut = offset + sizeof(Single);
                        break;
                    }
                case TypeCode.Int32:
                    {
                        temp = BitConverter.GetBytes((Int32)basicType);
                        Array.Reverse(temp);
                        Array.Copy(temp, 0, bufOut, offset, sizeof(Int32));
                        endOffsetOut = offset + sizeof(Int32);
                        break;
                    }
                case TypeCode.UInt32:
                    {
                        temp = BitConverter.GetBytes((UInt32)basicType);
                        Array.Reverse(temp);
                        Array.Copy(temp, 0, bufOut, offset, sizeof(UInt32));
                        endOffsetOut = offset + sizeof(UInt32);
                        break;
                    }
                case TypeCode.Int16:
                    {
                        temp = BitConverter.GetBytes((Int16)basicType);
                        Array.Reverse(temp);
                        Array.Copy(temp, 0, bufOut, offset, sizeof(Int16));
                        endOffsetOut = offset + sizeof(Int16);
                        break;
                    }
                case TypeCode.UInt16:
                    {
                        temp = BitConverter.GetBytes((UInt16)basicType);
                        Array.Reverse(temp);
                        Array.Copy(temp, 0, bufOut, offset, sizeof(UInt16));
                        endOffsetOut = offset + sizeof(UInt16);
                        break;
                    }
                case TypeCode.Int64:
                    {
                        temp = BitConverter.GetBytes((Int64)basicType);
                        Array.Reverse(temp);
                        Array.Copy(temp, 0, bufOut, offset, sizeof(Int64));
                        endOffsetOut = offset + sizeof(Int64);
                        break;
                    }
                case TypeCode.UInt64:
                    {
                        temp = BitConverter.GetBytes((UInt64)basicType);
                        Array.Reverse(temp);
                        Array.Copy(temp, 0, bufOut, offset, sizeof(UInt64));
                        endOffsetOut = offset + sizeof(UInt64);
                        break;
                    }
                case TypeCode.Double:
                    {
                        temp = BitConverter.GetBytes((Double)basicType);
                        Array.Reverse(temp);
                        Array.Copy(temp, 0, bufOut, offset, sizeof(Double));
                        endOffsetOut = offset + sizeof(Double);
                        break;
                    }
                case TypeCode.Byte:
                    {
                        bufOut[offset] = (Byte)basicType;
                        endOffsetOut = offset + 1;
                        break;
                    }
                default:
                    {
                        //System.Diagnostics.Debug.Fail("No conversion provided for this type : " + typeCode.ToString());
                        //break;
                        endOffsetOut = startOffset;
                        return false;
                    }
            }; // switch

            return true;
        }

        /*
         *
         * 将数组从起始位置，转换到基本数据类型,注意转换后 buf中的数据被改变字节序
         * basicType     转换的数据类型
         * buf           需要转换的缓冲区 
         * startOffset   转换的起始偏移量
         * endOffsetOut  endOffsetOut[0] 转换后缓冲区中的偏移量
         * */
        public static object ByteArrayToBiscTypeInBigEnd(object basicType, byte[] buf, int startOffset, out int endOffsetOut)
        {
            TypeCode typeCode;
            typeCode = Type.GetTypeCode(basicType.GetType());  // get type
            int offset = startOffset;

            switch (typeCode)
            {
                case TypeCode.Single: // float
                    {
                        //转换字节序
                        Array.Reverse(buf, offset, sizeof(Single));
                        endOffsetOut = offset + sizeof(Single);
                        return BitConverter.ToSingle(buf, offset);
                    }
                case TypeCode.Int32:
                    {
                        Array.Reverse(buf, offset, sizeof(Int32));
                        endOffsetOut = offset + sizeof(Int32);
                        return BitConverter.ToInt32(buf, offset);
                    }
                case TypeCode.UInt32:
                    {
                        Array.Reverse(buf, offset, sizeof(UInt32));
                        endOffsetOut = offset + sizeof(UInt32);
                        //tmp = BitConverter.ToUInt32(buf, offset);
                        return BitConverter.ToUInt32(buf, offset);
                    }
                case TypeCode.Int16:
                    {
                        Array.Reverse(buf, offset, sizeof(Int16));
                        endOffsetOut = offset + sizeof(Int16);
                        return BitConverter.ToInt16(buf, offset);
                    }
                case TypeCode.UInt16:
                    {
                        Array.Reverse(buf, offset, sizeof(UInt16));
                        endOffsetOut = offset + sizeof(UInt16);
                        return BitConverter.ToUInt16(buf, offset);
                    }
                case TypeCode.Int64:
                    {
                        Array.Reverse(buf, offset, sizeof(Int64));
                        endOffsetOut = offset + sizeof(Int64);
                        return BitConverter.ToInt64(buf, offset);
                    }
                case TypeCode.UInt64:
                    {
                        Array.Reverse(buf, offset, sizeof(UInt64));
                        endOffsetOut = offset + sizeof(UInt64);
                        return BitConverter.ToInt64(buf, offset);
                    }
                case TypeCode.Double:
                    {
                        Array.Reverse(buf, offset, sizeof(Double));
                        endOffsetOut = offset + sizeof(Double);
                        return BitConverter.ToDouble(buf, offset);
                    }
                case TypeCode.Byte:
                    {
                        //buf[offset] = (Byte)basicType;
                        endOffsetOut = offset + 1;
                        return buf[offset];
                    }
                default:
                    {
                        endOffsetOut = startOffset;
                        return null;
                    }
            } // switch           
        }
        #endregion

        #region 数组转字符串 字符串转数组

        public static string ByteArrayToHexString(byte[] bytes, int nLen = 0, string strSplitMark = "")
        {
            string retStr = "";
            if (bytes != null)
            {
                if (nLen == 0)
                {
                    nLen = bytes.Length;
                }
                for (int i = 0; i < nLen; i++)
                {
                    retStr += bytes[i].ToString("X2") + strSplitMark;
                }
            }
            return retStr;
        }

        public static byte[] StringToByteArray(string strValue, System.Text.Encoding encode/* = Encoding.Unicode*/)
        {
            int nStrLen = strValue.Length;
            //nStrLen = Math.Min(byLen / 1, nStrLen);
            byte[] temp = null;
            temp = encode.GetBytes(strValue/*.Substring(0, nStrLen)*/);
            return temp;
        }

        public static string ByteArrayToString(byte[] brValue, System.Text.Encoding encode/* = Encoding.Unicode*/)
        {
            string strValue = "";
            strValue = encode.GetString(brValue);
            return strValue;
        }
        #endregion

        #region 字符串安全转Byte UInt16 UInt32
        public static Byte StringToByte(string strValue)
        {
            //屏蔽所有空格
            strValue = strValue.Replace(" ", "");

            Byte byValue = 0;
            try
            {
                byValue = Byte.Parse(strValue);
            }
            catch (System.OverflowException)
            {
                byValue = Byte.MaxValue;
            }
            catch (System.FormatException)
            {
                byValue = Byte.MinValue;
            }
            finally
            {
                ;
            }
            return byValue;
        }

        public static Byte HexStringToByte(string strHexValue)
        {
            //屏蔽所有空格
            strHexValue = strHexValue.Replace(" ", "");
            //大写
            strHexValue = strHexValue.ToLower();
            //去掉头部的0x
            strHexValue = strHexValue.Substring(strHexValue.IndexOf("x") + 1);

            Byte byValue = 0;
            try
            {
                byValue = Convert.ToByte(strHexValue, 16);
            }
            catch (System.OverflowException)
            {
                byValue = Byte.MaxValue;
            }
            catch (System.FormatException)
            {
                byValue = Byte.MinValue;
            }
            finally
            {
                ;
            }
            return byValue;
            //return Convert.ToByte(strHexValue.Substring(2, 2), 16);
        }

        public static UInt16 HexStringToUInt16(string strHexValue)
        {
            //屏蔽所有空格
            strHexValue = strHexValue.Replace(" ", "");
            //大写
            strHexValue = strHexValue.ToLower();
            //去掉头部的0x
            strHexValue = strHexValue.Substring(strHexValue.IndexOf("x") + 1);

            UInt16 uiValue = 0;
            try
            {
                uiValue = Convert.ToUInt16(strHexValue, 16);
            }
            catch (System.OverflowException)
            {
                uiValue = UInt16.MaxValue;
            }
            catch (System.FormatException)
            {
                uiValue = UInt16.MinValue;
            }
            finally
            {
                ;
            }
            return uiValue;
            //return Convert.ToByte(strHexValue.Substring(2, 2), 16);
        }

        public static UInt32 HexStringToUInt32(string strHexValue)
        {
            //屏蔽所有空格
            strHexValue = strHexValue.Replace(" ", "");
            //大写
            strHexValue = strHexValue.ToLower();
            //去掉头部的0x
            strHexValue = strHexValue.Substring(strHexValue.IndexOf("x") + 1);

            UInt32 unValue = 0;
            try
            {
                unValue = Convert.ToUInt32(strHexValue, 16);
            }
            catch (System.OverflowException)
            {
                unValue = UInt32.MaxValue;
            }
            catch (System.FormatException)
            {
                unValue = UInt32.MinValue;
            }
            finally
            {
                ;
            }
            return unValue;
            //return Convert.ToByte(strHexValue.Substring(2, 2), 16);
        }

        public static Int32 HexStringToInt32(string strHexValue)
        {
            //屏蔽所有空格
            strHexValue = strHexValue.Replace(" ", "");
            //大写
            strHexValue = strHexValue.ToLower();
            //去掉头部的0x
            strHexValue = strHexValue.Substring(strHexValue.IndexOf("x") + 1);

            Int32 unValue = 0;
            try
            {
                unValue = Convert.ToInt32(strHexValue, 16);
            }
            catch (System.OverflowException)
            {
                unValue = Int32.MaxValue;
            }
            catch (System.FormatException)
            {
                unValue = Int32.MinValue;
            }
            finally
            {
                ;
            }
            return unValue;
            //return Convert.ToByte(strHexValue.Substring(2, 2), 16);
        }

        public static UInt16 StringToUInt16(string strValue)
        {
            //屏蔽所有空格
            strValue = strValue.Replace(" ", "");

            UInt16 uiValue = 0;
            try
            {
                uiValue = UInt16.Parse(strValue);
            }
            catch (System.OverflowException)
            {
                uiValue = UInt16.MaxValue;
            }
            catch (System.FormatException)
            {
                uiValue = UInt16.MinValue;
            }
            finally
            {
                ;
            }
            return uiValue;
        }

        public static UInt32 StringToUInt32(string strValue)
        {
            //屏蔽所有空格
            strValue = strValue.Replace(" ", "");

            UInt32 uiValue = 0;
            try
            {
                uiValue = UInt32.Parse(strValue);
            }
            catch (System.OverflowException)
            {
                uiValue = UInt32.MaxValue;
            }
            catch (System.FormatException)
            {
                uiValue = UInt16.MinValue;
            }
            finally
            {
                ;
            }
            return uiValue;
        }

        public static Int32 StringToInt32(string strValue)
        {
            //屏蔽所有空格
            strValue = strValue.Replace(" ", "");

            Int32 iValue = 0;
            try
            {
                iValue = Int32.Parse(strValue);
            }
            catch (System.OverflowException)
            {
                iValue = Int32.MaxValue;
            }
            catch (System.FormatException)
            {
                iValue = Int32.MinValue;
            }
            finally
            {
                ;
            }
            return iValue;
        }

        public static Double StringToDouble(string strValue)
        {
            //屏蔽所有空格
            strValue = strValue.Replace(" ", "");

            Double dValue = 0;
            try
            {
                dValue = Double.Parse(strValue);
            }
            catch (System.OverflowException)
            {
                dValue = Double.MaxValue;
            }
            catch (System.FormatException)
            {
                dValue = Double.MinValue;
            }
            finally
            {
                ;
            }
            return dValue;
        }
        #endregion

        #region UInt16 Byte UInt32转字节数组
        public static byte[] Uint16ToByteArrayLittleEnd(UInt16 uiValue)
        {
            byte[] temp = BitConverter.GetBytes(uiValue);
            return temp;
        }

        public static byte[] Uint32ToByteArrayLittleEnd(UInt32 uiValue)
        {
            byte[] temp = BitConverter.GetBytes(uiValue);
            return temp;
        }

        public static byte[] Uint16ToByteArrayBigEnd(UInt16 uiValue)
        {
            UInt16 uiReverseValue = (UInt16)((uiValue & 0xFFU) << 8 | (uiValue & 0xFF00U) >> 8);
            byte[] temp = BitConverter.GetBytes(uiReverseValue);
            return temp;
        }

        public static byte[] Uint32ToByteArrayBigEnd(UInt32 uiValue)
        {
            UInt32 uiReverseValue = (uiValue & 0x000000FFU) << 24 | (uiValue & 0x0000FF00U) << 8 | (uiValue & 0x00FF0000U) >> 8 | (uiValue & 0xFF000000U) >> 24;
            byte[] temp = BitConverter.GetBytes(uiReverseValue);
            return temp;
        }

        public static UInt16 ByteArrayToUint16LittleEnd(byte[] byValue)
        {
            UInt16 uiTemp = BitConverter.ToUInt16(byValue, 0);
            return uiTemp;
        }

        public static UInt16 ByteArrayToUint16LittleEnd(byte byValue1, byte byValue2)
        {
            byte[] byTemp = new byte[2];
            byTemp[0] = byValue1;
            byTemp[1] = byValue2;

            return ByteArrayToUint16LittleEnd(byTemp);
        }

        public static UInt16 ByteArrayToUint16BigEnd(byte[] byValue)
        {
            if (byValue.Length < 2)
            {
                UInt16 uiTemp = (UInt16)((byte)(byValue[0] & 0x00ff));
                return uiTemp;
                //(UInt16)((UInt16)(Communication.scanDstNetAddr << 8 & 0xff00) + (byte)(curSelPhyDev.phyCmpnt.GetAddr() & 0x00ff));
            }
            else
            {
                UInt16 uiTemp = (UInt16)((UInt16)(byValue[0] << 8 & 0xff00) + (byte)(byValue[1] & 0x00ff));
                return uiTemp;
                //(UInt16)((UInt16)(Communication.scanDstNetAddr << 8 & 0xff00) + (byte)(curSelPhyDev.phyCmpnt.GetAddr() & 0x00ff));
            }
        }

        public static UInt16 ByteArrayToUint16BigEnd(byte byValue1, byte byValue2)
        {
            byte[] byTemp = new byte[2];
            byTemp[0] = byValue1;
            byTemp[1] = byValue2;

            return ByteArrayToUint16BigEnd(byTemp);
        }

        public static UInt32 ByteArrayToUint32LittleEnd(byte[] byValue)
        {
            UInt32 uiTemp = BitConverter.ToUInt32(byValue, 0);
            return uiTemp;
        }

        public static UInt32 ByteArrayToUint32LittleEnd(byte byValue1, byte byValue2, byte byValue3, byte byValue4)
        {
            byte[] byTemp = new byte[4];
            byTemp[0] = byValue1;
            byTemp[1] = byValue2;
            byTemp[2] = byValue3;
            byTemp[3] = byValue4;

            return ByteArrayToUint32LittleEnd(byTemp);
        }

        public static UInt32 ByteArrayToUint32BigEnd(byte[] byValue)
        {
            UInt32 uiTemp = (UInt32)((UInt32)(byValue[0] << 24 & 0xff000000) + (UInt32)(byValue[1] << 16 & 0xff0000) + (UInt32)(byValue[2] << 8 & 0xff00) + (byte)(byValue[3] & 0x00ff));
            return uiTemp;
        }

        public static UInt32 ByteArrayToUint32BigEnd(byte byValue1, byte byValue2, byte byValue3, byte byValue4)
        {
            byte[] byTemp = new byte[4];
            byTemp[0] = byValue1;
            byTemp[1] = byValue2;
            byTemp[2] = byValue3;
            byTemp[3] = byValue4;

            return ByteArrayToUint32BigEnd(byTemp);
        }
        #endregion

        #region IP相关功能帮助函数
        public static List<string> GetIPAddress()
        {
            List<string> ipAddress = new List<string>();
            System.Net.IPHostEntry IpEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
            for (int i = 0; i != IpEntry.AddressList.Length; i++)
            {
                if (!IpEntry.AddressList[i].IsIPv6LinkLocal && !IpEntry.AddressList[i].IsIPv6Teredo)
                {
                    ipAddress.Add(IpEntry.AddressList[i].ToString());
                }
            }
            return ipAddress;
        }

        public static bool IsRightIP(string strIPadd)
        {
            //利用正则表达式判断字符串是否符合IPv4格式
            if (Regex.IsMatch(strIPadd, "[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}"))
            {
                //根据小数点分拆字符串
                string[] ips = strIPadd.Split('.');
                if (ips.Length == 4 || ips.Length == 6)
                {
                    //如果符合IPv4规则
                    if (System.Int32.Parse(ips[0]) < 256 && System.Int32.Parse(ips[1]) < 256 & System.Int32.Parse(ips[2]) < 256 & System.Int32.Parse(ips[3]) < 256)
                        //正确
                        return true;
                    //如果不符合
                    else
                        //错误
                        return false;
                }
                else
                    //错误
                    return false;
            }
            else
                //错误
                return false;
        }

        public static void GetNetCardInfo()
        {
            //获取本地计算机上网络接口的对象
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
            Console.WriteLine("适配器个数：" + adapters.Length);
            foreach (NetworkInterface adapter in adapters)
            {
                Console.WriteLine("描述：" + adapter.Description);
                Console.WriteLine("标识符：" + adapter.Id);
                Console.WriteLine("名称：" + adapter.Name);
                Console.WriteLine("类型：" + adapter.NetworkInterfaceType);
                Console.WriteLine("速度：" + adapter.Speed * 0.001 * 0.001 + "M");
                Console.WriteLine("操作状态：" + adapter.OperationalStatus);
                //Console.WriteLine("MAC 地址：" + adapter.GetPhysicalAddress());

                if (adapter.OperationalStatus == System.Net.NetworkInformation.OperationalStatus.Up)
                {
                    Console.WriteLine("当前正在连接");

                    //if (adapter.NetworkInterfaceType.ToString().Equals("Ethernet"))
                    {
                        //adapter.Name;     //网卡适配名称：“本地连接”
                        //adapter.Description;   //适配器描述信息
                        IPInterfaceProperties ip = adapter.GetIPProperties();     //IP配置信息
                        if (ip.UnicastAddresses.Count > 0)
                        {
                            ip.UnicastAddresses[0].Address.ToString();   //IP地址
                            ip.UnicastAddresses[0].IPv4Mask.ToString();  //子网掩码
                        }
                        if (ip.GatewayAddresses.Count > 0)
                            ip.GatewayAddresses[0].Address.ToString();   //默认网关
                        if (ip.DnsAddresses.Count > 0)
                        {
                            ip.DnsAddresses[0].ToString();       //首选DNS服务器地址
                            if (ip.DnsAddresses.Count > 1)
                                ip.DnsAddresses[1].ToString();  //备用DNS服务器地址
                        }
                    }
                }
                else
                {
                    Console.WriteLine("当前处于静止或者中断状态");
                }

                // 格式化显示MAC地址                
                PhysicalAddress pa = adapter.GetPhysicalAddress();//获取适配器的媒体访问（MAC）地址
                byte[] bytes = pa.GetAddressBytes();//返回当前实例的地址
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < bytes.Length; i++)
                {
                    sb.Append(bytes[i].ToString("X2"));//以十六进制格式化
                    if (i != bytes.Length - 1)
                    {
                        sb.Append("-");
                    }
                }
                Console.WriteLine("MAC 地址：" + sb);
                Console.WriteLine();
            }

            //与上面一样，只不过用了Dns.GetHostAddresses()的方法  
            IPAddress[] dnsIps = Dns.GetHostAddresses(Dns.GetHostName());
            for (int i = 0; i < dnsIps.Length; i++)
            {
                if (dnsIps[i].AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    //netInfo += "\r\nDns.GetHostAddresses()得到本机正在使用的IP为：" + dnsIps[i].ToString();
                    dnsIps[i].ToString();
                }
            }
            Console.ReadKey();
        }

        private static HttpServer httpServer = null;
        public static void StartHttpServer(System.Windows.Controls.UserControl control, int nPort = 8080)
        {
            //若Port与当前一致，则不再次开启

            if (httpServer != null)
            {
                if (httpServer.nPort == nPort)
                    return;
                else
                {
                    StopHttpServer();
                }
            }


            //构建HttpServer
            httpServer = new HttpServerEx(control, nPort);

            //开启监控线程
            Thread thread = new Thread(new ThreadStart(httpServer.Listen));
            thread.Start();
        }

        public static void StopHttpServer()
        {
            if (httpServer != null)
                httpServer.Exit();

            httpServer = null;
        }
        #endregion

        #region Excel
        public static void WriteExcel(DataTable dateTable, string filePath)
        {
            /*
             * public static DataTable dataTableWifi = null;//new DataTable("1_6_GetResult");
                dataTableWifi = new DataTable("1_6_GetResult");
                dataTableWifi.Columns.Add(new DataColumn("TotalMsgNum", typeof(string)));
                dataTableWifi.Columns.Add(new DataColumn("RecPkgNum", typeof(string)));
                dataTableWifi.Columns.Add(new DataColumn("DevAddr", typeof(string)));
                dataTableWifi.Columns.Add(new DataColumn("NodeType", typeof(string)));
                dataTableWifi.Rows.Add(ulTotalMsgNum, RecPkgNum,DevAddr, NodeType);
                 if (dataTableWifi != null)
                    dataTableWifi.Clear();
             * */
            if (!string.IsNullOrEmpty(filePath) && null != dateTable && dateTable.Rows.Count > 0)
            {
                /*
                 * 
                if (fileName.IndexOf(".xlsx") > 0) // 2007版本
                    workbook = new XSSFWorkbook();
                else if (fileName.IndexOf(".xls") > 0) // 2003版本
                    workbook = new HSSFWorkbook();
                 * */
                HSSFWorkbook book = new HSSFWorkbook();
                ISheet sheet = book.CreateSheet(dateTable.TableName);

                //单元格居中
                ICellStyle cellstyle = book.CreateCellStyle();
                cellstyle.VerticalAlignment = VerticalAlignment.Center;
                cellstyle.Alignment = HorizontalAlignment.Center;
                cellstyle.WrapText = true;//设置换行这个要先设置

                NPOI.SS.UserModel.IRow row = sheet.CreateRow(0);
                for (int i = 0; i < dateTable.Columns.Count; i++)
                {
                    //列宽自适应，只对英文和数字有效
                    sheet.AutoSizeColumn(i);

                    ICell cell = row.CreateCell(i);
                    cell.SetCellValue(dateTable.Columns[i].ColumnName);
                    cell.CellStyle = cellstyle;
                }
                for (int i = 0; i < dateTable.Rows.Count; i++)
                {
                    NPOI.SS.UserModel.IRow row2 = sheet.CreateRow(i + 1);
                    for (int j = 0; j < dateTable.Columns.Count; j++)
                    {
                        ICell cell = row2.CreateCell(j);
                        cell.SetCellValue(Convert.ToString(dateTable.Rows[i][j]));
                        cell.CellStyle = cellstyle;
                    }
                }

                //获取当前列的宽度，然后对比本列的长度，取最大值
                //for (int columnNum = 0; columnNum <= dateTable.Rows.Count; columnNum++)
                //{
                //    int columnWidth = sheet.GetColumnWidth(columnNum) / 256;
                //    for (int rowNum = 1; rowNum <= sheet.LastRowNum; rowNum++)
                //    {
                //        IRow currentRow;
                //        //当前行未被使用过
                //        if (sheet.GetRow(rowNum) == null)
                //        {
                //            currentRow = sheet.CreateRow(rowNum);
                //        }
                //        else
                //        {
                //            currentRow = sheet.GetRow(rowNum);
                //        }

                //        if (currentRow.GetCell(columnNum) != null)
                //        {
                //            ICell currentCell = currentRow.GetCell(columnNum);
                //            int length = Encoding.Default.GetBytes(currentCell.ToString()).Length;
                //            if (columnWidth < length)
                //            {
                //                columnWidth = length;
                //            }
                //        }
                //    }
                //    sheet.SetColumnWidth(columnNum, columnWidth * 256);
                //}

                // 写入到客户端  
                using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                {
                    book.Write(ms);
                    using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write))
                    {
                        byte[] data = ms.ToArray();
                        fs.Write(data, 0, data.Length);
                        fs.Flush();
                    }
                    book = null;
                }
            }
        }

        public static HSSFWorkbook WriteExcelExtern(HSSFWorkbook book, string strMac, string strAliasName, string strImei, string strTotalTime, string strAvgValue, DataTable dateTable, int nIndex, string filePath)
        {
            if (!string.IsNullOrEmpty(filePath) && null != dateTable && dateTable.Rows.Count > 0)
            {
                /*
                 * 
                if (fileName.IndexOf(".xlsx") > 0) // 2007版本
                    workbook = new XSSFWorkbook();
                else if (fileName.IndexOf(".xls") > 0) // 2003版本
                    workbook = new HSSFWorkbook();
                 * */
                if (book == null)
                {
                    book = new HSSFWorkbook();
                }
                //HSSFWorkbook book = new HSSFWorkbook();
                ISheet sheet = book.GetSheet(dateTable.TableName);//book.CreateSheet(dateTable.TableName);
                if (sheet == null)
                {
                    sheet = book.CreateSheet(dateTable.TableName);
                }

                int nGap = nIndex * 5;

                //单元格居中
                ICellStyle cellstyle = book.CreateCellStyle();
                cellstyle.VerticalAlignment = VerticalAlignment.Center;
                cellstyle.Alignment = HorizontalAlignment.Center;
                cellstyle.WrapText = true;//设置换行这个要先设置

                ICellStyle cellstyleTitle = book.CreateCellStyle();
                cellstyleTitle.VerticalAlignment = VerticalAlignment.Center;
                cellstyleTitle.Alignment = HorizontalAlignment.Center;
                cellstyleTitle.WrapText = true;//设置换行这个要先设置
                cellstyleTitle.FillForegroundColor = HSSFColor.PaleBlue.Index;
                cellstyleTitle.FillPattern = FillPattern.SolidForeground;

                #region
                //row 0
                NPOI.SS.UserModel.IRow row = sheet.GetRow(0);// sheet.CreateRow(0);
                if (row == null)
                {
                    row = sheet.CreateRow(0);
                }
                ICell cell = row.GetCell(nGap + 0);// row.CreateCell(0);
                if (cell == null)
                {
                    cell = row.CreateCell(nGap + 0);//
                }
                cell.SetCellValue("mac");
                cell.CellStyle = cellstyleTitle;

                cell = row.GetCell(nGap + 1);// row.CreateCell(0);
                if (cell == null)
                {
                    cell = row.CreateCell(nGap + 1);//
                }
                //cell = row.CreateCell(1);
                cell.SetCellValue("别名");
                cell.CellStyle = cellstyleTitle;

                cell = row.GetCell(nGap + 2);// row.CreateCell(0);
                if (cell == null)
                {
                    cell = row.CreateCell(nGap + 2);//
                }
                //cell = row.CreateCell(2);
                cell.SetCellValue("imei");
                cell.CellStyle = cellstyleTitle;

                //row 1
                row = sheet.GetRow(1);
                if (row == null)
                {
                    row = sheet.CreateRow(1);
                }

                cell = row.GetCell(nGap + 0);// row.CreateCell(0);
                if (cell == null)
                {
                    cell = row.CreateCell(nGap + 0);//
                }
                //cell = row.CreateCell(0);
                cell.SetCellValue(strMac);
                cell.CellStyle = cellstyle;

                cell = row.GetCell(nGap + 1);// row.CreateCell(0);
                if (cell == null)
                {
                    cell = row.CreateCell(nGap + 1);//
                }
                //cell = row.CreateCell(1);
                cell.SetCellValue(strAliasName);
                cell.CellStyle = cellstyle;

                cell = row.GetCell(nGap + 2);// row.CreateCell(0);
                if (cell == null)
                {
                    cell = row.CreateCell(nGap + 2);//
                }
                //cell = row.CreateCell(2);
                cell.SetCellValue(strImei);
                cell.CellStyle = cellstyle;

                //row 2
                row = sheet.GetRow(2);
                if (row == null)
                {
                    row = sheet.CreateRow(2);
                }
                //row = sheet.CreateRow(2);

                cell = row.GetCell(nGap + 0);// row.CreateCell(0);
                if (cell == null)
                {
                    cell = row.CreateCell(nGap + 0);//
                }
                //cell = row.CreateCell(0);
                cell.SetCellValue("TotalCount");
                cell.CellStyle = cellstyleTitle;

                cell = row.GetCell(nGap + 1);// row.CreateCell(0);
                if (cell == null)
                {
                    cell = row.CreateCell(nGap + 1);//
                }
                //cell = row.CreateCell(0);
                cell.SetCellValue("TotalTime");
                cell.CellStyle = cellstyleTitle;

                cell = row.GetCell(nGap + 2);// row.CreateCell(0);
                if (cell == null)
                {
                    cell = row.CreateCell(nGap + 2);//
                }
                //cell = row.CreateCell(1);
                cell.SetCellValue("平均值");
                cell.CellStyle = cellstyleTitle;

                //row 3
                row = sheet.GetRow(3);
                if (row == null)
                {
                    row = sheet.CreateRow(3);
                }
                //row = sheet.CreateRow(3);

                cell = row.GetCell(nGap + 0);// row.CreateCell(0);
                if (cell == null)
                {
                    cell = row.CreateCell(nGap + 0);//
                }
                //cell = row.CreateCell(0);
                cell.SetCellValue(dateTable.Rows.Count.ToString());
                cell.CellStyle = cellstyle;

                cell = row.GetCell(nGap + 1);// row.CreateCell(0);
                if (cell == null)
                {
                    cell = row.CreateCell(nGap + 1);//
                }
                //cell = row.CreateCell(0);
                cell.SetCellValue(strTotalTime);
                cell.CellStyle = cellstyle;

                cell = row.GetCell(nGap + 2);// row.CreateCell(0);
                if (cell == null)
                {
                    cell = row.CreateCell(nGap + 2);//
                }
                //cell = row.CreateCell(1);
                cell.SetCellValue(strAvgValue);
                cell.CellStyle = cellstyle;
                #endregion

                //row 4 and next
                row = sheet.GetRow(4);
                if (row == null)
                {
                    row = sheet.CreateRow(4);
                }
                //row = sheet.CreateRow(4);
                for (int i = 0; i < dateTable.Columns.Count; i++)
                {
                    //列宽自适应，只对英文和数字有效
                    sheet.AutoSizeColumn(i);

                    cell = row.GetCell(nGap + i);// row.CreateCell(0);
                    if (cell == null)
                    {
                        cell = row.CreateCell(nGap + i);//
                    }
                    //cell = row.CreateCell(i);
                    cell.SetCellValue(dateTable.Columns[i].ColumnName);
                    cell.CellStyle = cellstyleTitle;
                }
                for (int i = 0; i < dateTable.Rows.Count; i++)
                {
                    row = sheet.GetRow(i + 5);
                    if (row == null)
                    {
                        row = sheet.CreateRow(i + 5);
                    }
                    //row = sheet.CreateRow(i + 5);
                    for (int j = 0; j < dateTable.Columns.Count; j++)
                    {
                        cell = row.GetCell(nGap + j);// row.CreateCell(0);
                        if (cell == null)
                        {
                            cell = row.CreateCell(nGap + j);//
                        }
                        //cell = row.CreateCell(j);
                        cell.SetCellValue(Convert.ToString(dateTable.Rows[i][j]));
                        cell.CellStyle = cellstyle;
                    }
                }

                // 写入到客户端  
                using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                {
                    book.Write(ms);
                    using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write))
                    {
                        byte[] data = ms.ToArray();
                        fs.Write(data, 0, data.Length);
                        fs.Flush();
                    }
                    //book = null;
                }

                return book;
            }
            else
            {
                return null;
            }
        }

        public static void WriteExcelExtern1(DataTable dateTable, string filePath)
        {
            /*
             * public static DataTable dataTableWifi = null;//new DataTable("1_6_GetResult");
                dataTableWifi = new DataTable("1_6_GetResult");
                dataTableWifi.Columns.Add(new DataColumn("TotalMsgNum", typeof(string)));
                dataTableWifi.Columns.Add(new DataColumn("RecPkgNum", typeof(string)));
                dataTableWifi.Columns.Add(new DataColumn("DevAddr", typeof(string)));
                dataTableWifi.Columns.Add(new DataColumn("NodeType", typeof(string)));
                dataTableWifi.Rows.Add(ulTotalMsgNum, RecPkgNum,DevAddr, NodeType);
                 if (dataTableWifi != null)
                    dataTableWifi.Clear();
             * */
            if (!string.IsNullOrEmpty(filePath) && null != dateTable && dateTable.Rows.Count > 0)
            {
                /*
                 * 
                if (fileName.IndexOf(".xlsx") > 0) // 2007版本
                    workbook = new XSSFWorkbook();
                else if (fileName.IndexOf(".xls") > 0) // 2003版本
                    workbook = new HSSFWorkbook();
                 * */
                HSSFWorkbook book = new HSSFWorkbook();
                ISheet sheet = book.CreateSheet(dateTable.TableName);

                //单元格居中
                ICellStyle cellstyle = book.CreateCellStyle();
                cellstyle.VerticalAlignment = VerticalAlignment.Center;
                cellstyle.Alignment = HorizontalAlignment.Center;
                cellstyle.WrapText = true;//设置换行这个要先设置

                NPOI.SS.UserModel.IRow row = sheet.CreateRow(0);
                for (int i = 0; i < dateTable.Columns.Count; i++)
                {
                    //列宽自适应，只对英文和数字有效
                    //sheet.AutoSizeColumn(i);

                    //6.设置列宽   SetColumnWidth(列的索引号从0开始, N * 256) 第二个参数的单位是1/256个字符宽度。例：将第四列宽度设置为了30个字符。
                    sheet.SetColumnWidth(i, 30 * 256);

                    ICell cell = row.CreateCell(i);
                    cell.SetCellValue(dateTable.Columns[i].ColumnName);
                    cell.CellStyle = cellstyle;
                }
                sheet.SetColumnWidth(dateTable.Columns.Count - 1, 90 * 256);


                for (int i = 0; i < dateTable.Rows.Count; i++)
                {
                    NPOI.SS.UserModel.IRow row2 = sheet.CreateRow(i + 1);
                    for (int j = 0; j < dateTable.Columns.Count; j++)
                    {
                        ICell cell = row2.CreateCell(j);
                        cell.SetCellValue(Convert.ToString(dateTable.Rows[i][j]));
                        cell.CellStyle = cellstyle;
                    }
                }

                //获取当前列的宽度，然后对比本列的长度，取最大值
                //for (int columnNum = 0; columnNum <= dateTable.Rows.Count; columnNum++)
                //{
                //    int columnWidth = sheet.GetColumnWidth(columnNum) / 256;
                //    for (int rowNum = 1; rowNum <= sheet.LastRowNum; rowNum++)
                //    {
                //        IRow currentRow;
                //        //当前行未被使用过
                //        if (sheet.GetRow(rowNum) == null)
                //        {
                //            currentRow = sheet.CreateRow(rowNum);
                //        }
                //        else
                //        {
                //            currentRow = sheet.GetRow(rowNum);
                //        }

                //        if (currentRow.GetCell(columnNum) != null)
                //        {
                //            ICell currentCell = currentRow.GetCell(columnNum);
                //            int length = Encoding.Default.GetBytes(currentCell.ToString()).Length;
                //            if (columnWidth < length)
                //            {
                //                columnWidth = length;
                //            }
                //        }
                //    }
                //    sheet.SetColumnWidth(columnNum, columnWidth * 256);
                //}

                // 写入到客户端  
                using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                {
                    book.Write(ms);
                    using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write))
                    {
                        byte[] data = ms.ToArray();
                        fs.Write(data, 0, data.Length);
                        fs.Flush();
                    }
                    book = null;
                }
            }
        }

        public static void ReadExcel(DataTable dateTable, string filePath, int nTrueDataRowIndex = 1)
        {
            int startRow = 0;
            try
            {
                FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);

                string strFileExt = Path.GetExtension(filePath).ToLower();
                IWorkbook book = null;// new HSSFWorkbook(fs);

                //XSSFWorkbook 适用XLSX格式，HSSFWorkbook 适用XLS格式
                if (strFileExt == ".xlsx") 
                { 
                    book = new XSSFWorkbook(fs); 
                } 
                else if (strFileExt == ".xls") 
                { 
                    book = new HSSFWorkbook(fs); 
                } 
                else 
                { 
                    book = null;
                }
                if (book == null) 
                { 
                    return ; 
                }

                ISheet sheet = book.GetSheet(dateTable.TableName);
                if (sheet == null) //如果没有找到指定的sheetName对应的sheet，则尝试获取第一个sheet
                {
                    sheet = book.GetSheetAt(0);
                }

                if (sheet != null)
                {
                    IRow firstRow = sheet.GetRow(0);
                    int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数

                    startRow = sheet.FirstRowNum + nTrueDataRowIndex;

                    //最后一列的标号
                    int rowCount = sheet.LastRowNum;
                    for (int i = startRow; i <= rowCount; ++i)
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == null) continue; //没有数据的行默认是null　　　　　　　

                        DataRow dataRow = dateTable.NewRow();
                        for (int j = row.FirstCellNum; j < cellCount; ++j)
                        {
                            if (row.GetCell(j) != null) //同理，没有数据的单元格都默认是null
                                dataRow[j] = row.GetCell(j).ToString();
                        }
                        dateTable.Rows.Add(dataRow);
                    }
                }
                book.Close();
                fs.Close();
                return;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
                return;
            }
        }

        public static void ReadExcelForeachSheets(List<MainUIEx.ExcelSheet> excelSheetList, string filePath, int nTrueDataRowIndex = 1)
        {
            int startRow = 0;
            try
            {
                FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);

                string strFileExt = Path.GetExtension(filePath).ToLower();
                IWorkbook book = null;// new HSSFWorkbook(fs);

                //XSSFWorkbook 适用XLSX格式，HSSFWorkbook 适用XLS格式
                if (strFileExt == ".xlsx")
                {
                    book = new XSSFWorkbook(fs);
                }
                else if (strFileExt == ".xls")
                {
                    book = new HSSFWorkbook(fs);
                }
                else
                {
                    book = null;
                }
                if (book == null)
                {
                    return;
                }

                int nSheetCount = book.NumberOfSheets;
                for (int nSheetIndex = 0; nSheetIndex < nSheetCount; nSheetIndex++)
                {
                    //ISheet sheet = book.GetSheet(dateTable.TableName);
                    //if (sheet == null) //如果没有找到指定的sheetName对应的sheet，则尝试获取第一个sheet
                    //{
                    //    sheet = book.GetSheetAt(0);
                    //}

                    MainUIEx.ExcelSheet excelSheet = new MainUIEx.ExcelSheet();

                    ISheet sheet = book.GetSheetAt(nSheetIndex);
                    if (sheet != null)
                    {
                        excelSheet.strSheetName = sheet.SheetName;

                        IRow firstDataRow = sheet.GetRow(nTrueDataRowIndex);
                        int cellCount = firstDataRow.LastCellNum; //一行最后一个cell的编号 即总的列数

                        startRow = sheet.FirstRowNum + nTrueDataRowIndex;

                        //最后一列的标号
                        int rowCount = sheet.LastRowNum;
                        for (int i = startRow; i <= rowCount; ++i)
                        {
                            IRow row = sheet.GetRow(i);
                            if (row == null) continue; //没有数据的行默认是null　　　　　　　

                            DataRow dataRow = excelSheet.dataTable.NewRow();
                            for (int j = row.FirstCellNum; j < cellCount; ++j)
                            {
                                if (row.GetCell(j) != null) //同理，没有数据的单元格都默认是null
                                    dataRow[j] = row.GetCell(j).ToString();
                            }
                            excelSheet.dataTable.Rows.Add(dataRow);
                        }

                        excelSheetList.Add(excelSheet);
                    }
                }

                
                book.Close();
                fs.Close();
                return;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
                return;
            }
        }
        #endregion

        #region AppConfig
        public static string GetAppConfigValue(string strKey)
        {
            /*
             * 
             * <?xml version="1.0"?>
                <configuration>
                    <startup> 
                        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7"/>
                    </startup>
                  <appSettings>
                    <add key="ZebraPrinter" value="0" />
                  </appSettings>
                </configuration>
             * */

            //string strValue = System.Configuration.ConfigurationSettings.AppSettings[strKey];
            string strValue = System.Configuration.ConfigurationManager.AppSettings[strKey];
            return strValue;
        }

        //public static void SetAppConfigValue(string strKey, string strValue)
        //{
        //    /*
        //     * 
        //     * <?xml version="1.0"?>
        //        <configuration>
        //            <startup> 
        //                <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7"/>
        //            </startup>
        //          <appSettings>
        //            <add key="ZebraPrinter" value="0" />
        //          </appSettings>
        //        </configuration>
        //     * */

        //    System.Configuration.ConfigurationManager.AppSettings[strKey] = strValue;
        //}
        #endregion

        #region .net4.0 Task.Run
        public static Task TaskRun(Action action)
        {
            var tcs = new TaskCompletionSource<object>();
            new Thread(() =>
            {
                try
                {
                    action();
                    tcs.SetResult(null);
                }
                catch (Exception ex)
                {
                    System.Windows.MessageBox.Show(ex.Message);
                    tcs.SetException(ex);
                }
            }) { IsBackground = true }.Start();
            return tcs.Task;
        }
        #endregion

        #region 获取枚举描述
        ///// <summary>
        ///// 获得枚举的Description
        ///// </summary>
        ///// <param name="value">枚举值</param>
        ///// <param name="nameInstead">当枚举值没有定义DescriptionAttribute，是否使用枚举名代替，默认是使用</param>
        ///// <returns>枚举的Description</returns>
        //public static string GetDescription(this Enum value)
        //{
        //    Type type = value.GetType();
        //    string name = Enum.GetName(type, value);
        //    if (name == null)
        //    {
        //        return null;
        //    }

        //    FieldInfo field = type.GetField(name);
        //    DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;

        //    if (attribute == null)
        //    {
        //        return name;
        //    }
        //    return attribute == null ? null : attribute.Description;
        //}

        #endregion
    }

    public static class StringExtensions 
    { 
        public static string ToDescription(this Enum value) 
        { 
            if (value == null)                
                return ""; 
            
            System.Reflection.FieldInfo fieldInfo = value.GetType().GetField(value.ToString()); 
            if(fieldInfo == null)
                return value.ToString(); 
            object[] attribArray = fieldInfo.GetCustomAttributes(false); 
            if (attribArray.Length == 0)                
                return value.ToString(); 
            else                
                return (attribArray[0] as DescriptionAttribute).Description; 
        } 
    }
}
